<template>
  <div
    class="upload-one"
    @mouseenter="mouseenter"
    @mouseleave="mouseleave"
    @paste="e => pasteImg(e)"
  >
    <ul class="upload-one">
      <li
        :style="{ width: width + 'px', height: width + 'px' }"
        class="upload-one"
      >
        <div class="upload-info" @click="uploadImg">
          <div class="img-inline-block">
            <div v-if="value__">
              <span>
                <a-icon
                  title="查看"
                  type="eye"
                  class="fs16"
                  :class="width < 100 ? 'mr4' : 'mr10'"
                  @click.stop="view()"
                />
                <a-icon
                  title="删除"
                  type="delete"
                  class="fs16"
                  @click.stop="del"
                />
                <!-- <a-popconfirm
                  title="确定删除?"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="del">
                  <a-icon
                    title="删除"
                    type="delete" />
                </a-popconfirm> -->
              </span>
            </div>
            <img
              v-if="value__"
              :style="{
                maxWidth: width * 0.9 + 'px',
                maxHeight: width * 0.9 + 'px'
              }"
              :src="diffImg[ossSuffix] || value__"
              alt=""
            />
          </div>
          <a-progress
            v-if="percent"
            type="circle"
            :percent="percent"
            :width="width * 0.8"
          />
          <a-icon v-if="!value__ && !percent && !value__" type="plus" />
          <p v-if="width > 80 && !value__ && !percent">Upload</p>
        </div>
      </li>
    </ul>
    <input ref="upload" :accept="accept" hidden type="file" @change="load" />
    <a-modal
      v-model="visible"
      title="图片预览"
      :z-index="9999"
      :footer="null"
      width="600px"
    >
      <div>
        <img ref="img" style="width: 560px" :src="value__" alt="" />
        <p v-if="boolView">暂不支持该格式的文件预览</p>
      </div>
    </a-modal>
    <div style="z-index: -1; overflow: auto" class="d-relative">
      <input
        ref="inputText"
        style="font-size: initial"
        class="d-absolute"
        type="text"
      />
    </div>
  </div>
</template>
<script>
import axios from 'axios'
export default {
  props: {
    value: {
      type: String,
      default: ''
    },
    width: {
      type: Number,
      default: 100
    },
    imgSize: {
      type: Number,
      default: 10
    },
    accept: {
      type: String,
      default: '*'
    },
    uploadUrl: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      diffImg: {
        txt: 'https://cupshe-cdn.oss-cn-hangzhou.aliyuncs.com/web/images/txt.png',
        word: 'https://cupshe-cdn.oss-cn-hangzhou.aliyuncs.com/web/images/word.png',
        xlsx: 'https://cupshe-cdn.oss-cn-hangzhou.aliyuncs.com/web/images/excel.png',
        excel:
          'https://cupshe-cdn.oss-cn-hangzhou.aliyuncs.com/web/images/excel.png',
        pdf: 'https://cupshe-cdn.oss-cn-hangzhou.aliyuncs.com/web/images/pdf.png',
        zip: 'https://cupshe-cdn.oss-cn-hangzhou.aliyuncs.com/web/images/zip.png'
      },
      ossSuffix: '',
      visible: false,
      viewImg: '',
      current: 0,
      percent: 0,
      boolView: false,
      value__: ''
    }
  },
  watch: {
    value(v) {
      this.value__ = v
    }
  },
  created() {
    this.value__ = this.value
  },
  methods: {
    pasteImg(e) {
      const clipboardData = e.clipboardData || window.clipboardData
      console.log(clipboardData) // 查看clipboardData
      const items = clipboardData.items
      const types = clipboardData.types
      console.log(items, types)
      let file = null
      // 搜索剪切板items
      for (let i = 0; i < items.length; i++) {
        console.log(items[i])
        if (items[i].type.indexOf('image') !== -1) {
          file = items[i].getAsFile()
          // break
        } else {
          // clipboardData.clearData(items[i].type)
          var str = clipboardData.getData(items[i].type)
          console.log(str)
        }
      }
      if (!file) {
        this.$message.error('请粘贴图片')
        return
      }
      this.uploadAjax(file)
    },
    uploadImg(e) {
      this.$refs.upload.click()
    },
    del() {
      const that = this
      this.$confirm({
        content: '确定删除？',
        okType: 'danger',
        onOk() {
          that.value__ = ''
          that.$emit('input', '')
          that.$emit('getName', '')
          that.$emit('getImgInfo', {})
          that.$forceUpdate()
        }
      })
      // this.value__ = ''
      // this.$emit('input', '')
      // this.$emit('getName', '')
      // this.$forceUpdate()
    },
    view(img) {
      this.visible = true
      this.boolView = false
      setTimeout(() => {
        this.boolView = this.$refs.img.offsetHeight === 0
      }, 100)
    },
    mouseleave() {
      this.$refs.inputText.blur()
    },
    mouseenter() {
      // this.$refs.inputText.click()
      this.$refs.inputText.focus()
    },
    load(e) {
      // const { name: fileName, size } = e.target.files[0]
      this.uploadAjax(e.target.files[0])
    },
    uploadAjax(file) {
      const { name: fileName, size } = file
      if (
        this.accept !== '*' &&
        !this.accept.includes(
          fileName.split('.')[fileName.split('.').length - 1].toLowerCase()
        )
      ) {
        this.$message.error(`只支持${this.accept}文件格式`)
        this.$refs.upload.value = ''
        return
      }
      if (size / 1024 / 1024 > this.imgSize) {
        this.$message.error(`文件大小不能超过${this.imgSize}M`)
        this.$refs.upload.value = ''
        return
      }
      const self = this
      const formData = new FormData()
      formData.append('file', file)
      axios({
        url:
          localStorage.cpsurlimg ||
          this.uploadUrl ||
          process.env.VUE_APP_FILE ||
          'http://scm-develop.kapeixi.cn/oss/uploadFileToOss',
        method: 'post',
        onUploadProgress: function (progressEvent) {
          // 原生获取上传进度
          if (progressEvent.lengthComputable) {
            self.percent =
              parseInt((progressEvent.loaded / progressEvent.total) * 100) < 99
                ? parseInt((progressEvent.loaded / progressEvent.total) * 100)
                : 99
          }
        },
        headers: {
          'Content-Type': 'multipart/form-data',
          userId: localStorage.userId,
          token: localStorage.userId,
          Authorization: localStorage.token,
          tokenSign: 2,
          accountId: localStorage.accountId
        },
        data: formData
        //    withCredentials: true 指定域名
      }).then(res => {
        // e.target.value = ''
        console.dir(this.$refs.upload)
        this.$refs.upload.value = ''
        self.$emit('input', res.data.data.ossUrl)
        this.ossSuffix = res.data.data.ossSuffix
        this.$emit('getName', fileName)
        this.$emit('update:value', fileName)
        this.$emit('getImgInfo', res)
        self.percent = 0
      })
    }
  }
}
</script>
<style lang="less" scoped>
ul {
  padding-left: 0;
  margin: 0;
}
li {
  list-style-type: none;
  // width: 100px;
  // height: 100px;
  border: 1px dashed #999;
  background: #fafafa;
  // margin-right: 10px;
  overflow: hidden;
  text-align: center;
  // margin-bottom:10px;
  border-radius: 3px;
  &:hover {
    border: 1px dashed #1989fa;
  }
}
.upload-one {
  display: inline-block;
  & /deep/ .anticon-plus {
    font-size: 20px;
  }
}
.upload-info {
  display: flex;
  align-items: center;
  flex-direction: column;
  height: 100%;
  justify-content: center;
  opacity: 0.7;
  cursor: pointer;
  padding: 5px;
  & > img {
    min-width: 50px;
    transition: all 0.5s;
  }
}
.img-inline-block {
  position: relative;
  width: 100%;
  & > div {
    color: #999;
    font-size: 20px;
    position: absolute;
    background: rgba(0, 0, 0, 0.3);
    width: 100%;
    height: 100%;
    cursor: pointer;
    & > span {
      position: absolute;
      width: 100%;
      top: 50%;
      z-index: 333;
      left: 50%;
      transform: translate(-50%, -50%);
      color: #fff;
      &:hover {
        color: #1989fa;
      }
    }
  }
  img {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    margin: auto !important;
  }
}
</style>
